package umn.angrypenguins.monopoly.webservice;

import android.net.Uri;
import android.net.Uri.Builder;
import android.net.http.AndroidHttpClient;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import umn.angrypenguins.monopoly.models.GameInstance;
import umn.angrypenguins.monopoly.models.PlayerInstance;
import umn.angrypenguins.monopoly.utils.JsonSerializer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Chris Seeling
 * Date: 5/1/12
 * Time: 7:27 PM
 * To change this template use File | Settings | File Templates.
 */
public class WebServiceClient {

    private static final String URL_BASE = "http://monopolybankservice.cloudfoundry.com";
    //private static final String URL_BASE = "http://localhost:8080/MonopolyBankService";
    private static final String GAME_BASE = URL_BASE + "/game";
    private static final String PLAYER_BASE = URL_BASE + "/player";

    public static ArrayList<GameInstance> getAllGames() {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            HttpUriRequest request = new HttpGet(GAME_BASE);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            ArrayList<GameInstance> result = JsonSerializer.parseGames(json);

            client.close();
            
            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.GetAllGames", ex);
            return null;
        }
    }

    public static GameInstance findGame(String name) {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            Builder builder = Uri.parse( GAME_BASE ).buildUpon();
            builder.appendPath( "find" ).appendPath( name );
            
            String url = builder.toString();
            
            HttpUriRequest request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            GameInstance result = JsonSerializer.parseGameInstance(json);

            client.close();
            
            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.getGame", ex);
            return null;
        }
    }
    
    public static GameInstance getGame(int id) {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            HttpUriRequest request = new HttpGet(GAME_BASE + "?id=" + id);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            GameInstance result = JsonSerializer.parseGameInstance(json);

            client.close();
            
            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.getGame", ex);
            return null;
        }
    }

    public static GameInstance createGame(GameInstance game) {
        try {
            HttpClient client = new DefaultHttpClient();

            /*
            Builder builder = new Uri.Builder()
                    .scheme("http").authority("monopolybankservice.cloudfoundry.com").path("game").appendPath("create")
                    .appendQueryParameter("gameName", game.getName())
                    .appendQueryParameter("playerName", game.getCreator().getName())
                    .appendQueryParameter("wallet", game.getCreator().getWallet().toString());

            Builder builder = new Uri.Builder()
                    .scheme("http").authority("localhost").path("MonopolyBankService").appendPath("game").appendPath("create")
                    .appendQueryParameter("gameName", game.getName())
                    .appendQueryParameter("playerName", game.getCreator().getName())
                    .appendQueryParameter("startMoney", game.getCreator().getWallet().toString());
            */
            Builder builder = Uri.parse(URL_BASE).buildUpon();
            builder.appendPath("game").appendPath("createGame")
                    .appendQueryParameter("gameName", game.getName())
                    .appendQueryParameter("playerName", game.getCreator().getName())
                    .appendQueryParameter("startMoney", game.getCreator().getWallet().toString());
            Log.i("MonopolyMoney.WebServiceClient.createGame", "Url = " + builder.toString());
            String url = builder.toString();
            HttpPost request = new HttpPost(url);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            Log.i( "MonopolyMoney.WebServiceClient.createGame", "JSON = " + json );
            
            GameInstance result = JsonSerializer.parseGameInstance(json);

            Log.i("MonopolyMoney.WebServiceClient.createGame", "game successfully created, name = " + result.getName());
            return result;
        }
        catch (Exception ex) {
            Log.i("MonopolyMoney.WebServiceClient.createGame", ex.getMessage() );
            return null;
        }
    }

    public static ArrayList<PlayerInstance> getAllPlayers() {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            HttpUriRequest request = new HttpGet(PLAYER_BASE);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            ArrayList<PlayerInstance> result = JsonSerializer.parsePlayers(json);

            client.close();
            
            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.getAllPlayers", ex);
            return null;
        }
    }

    public static PlayerInstance getPlayer(int id) {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            HttpUriRequest request = new HttpGet(PLAYER_BASE + "?id=" + id);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            PlayerInstance result = JsonSerializer.parsePlayerInstance(json);

            client.close();
            
            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.getPlayer", ex);
            return null;
        }
    }

    public static ArrayList<PlayerInstance> makeTransfer(int fromPlayerId, int toPlayerId, int amount) {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            String url = PLAYER_BASE + "/transfer/" + fromPlayerId + "/" + toPlayerId + "/" + amount;
            HttpUriRequest request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();

            ArrayList<PlayerInstance> result = JsonSerializer.parsePlayers(json);

            client.close();
            
            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.makeTransfer", ex);
            return null;
        }
    }

    public static PlayerInstance joinGame(String gameName, String playerName) {
        try {
            AndroidHttpClient client = AndroidHttpClient.newInstance("MonopolyMoney");

            Builder builder = Uri.parse( PLAYER_BASE ).buildUpon();
            
            builder.appendPath( "addPlayerToGame" );
            builder.appendPath( gameName );
            builder.appendPath( playerName );
            
            String url = builder.toString();
            
            HttpPut request = new HttpPut(url);
            HttpResponse response = client.execute(request);

            BufferedReader webServiceReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String json = webServiceReader.readLine();
            webServiceReader.close();
            client.close();

            PlayerInstance result = JsonSerializer.parsePlayerInstance(json);

            return result;
        }
        catch (Exception ex) {
            Log.w("MonopolyMoney.WebServiceClient.joinGame", ex);
            return null;
        }
    }
}
